﻿using System;
using System.Web;
using PegasCompany.Data;

namespace PegasCompany.Tools.Storage
{
	public class CookieHelper
	{
		private enum Keys
		{
			Uid
		}

		private static HttpCookie Get(Keys cookieKey)
		{
			return HttpContext.Current.Request.Cookies[cookieKey.ToString()];
		}

		private static void Set(Keys cookieKey, object cookieValue)
		{
			HttpCookie aCookie = new HttpCookie(cookieKey.ToString());
			if (cookieValue != null)
			{
				aCookie.Values[cookieKey.ToString()] = cookieValue.ToString();
				HttpContext.Current.Response.Cookies.Add(aCookie);
			}
			else
			{
				HttpCookie savedCookie = HttpContext.Current.Request.Cookies[cookieKey.ToString()];
				if (savedCookie != null)
				{
					aCookie = new HttpCookie(savedCookie.Name);
					aCookie.Expires = DateTime.Now.AddDays(-1);
					HttpContext.Current.Response.Cookies.Add(aCookie);
				}
			}
		}

		public static SiteUserExtended CookieUser
		{
			get
			{
				HttpCookie cookieUser = Get(Keys.Uid);
				if (cookieUser != null)
				{
					string sUserId = CryptoHelper.Decrypt(Convert.FromBase64String(cookieUser.Value.Substring(Keys.Uid.ToString().Length + 1)));
					int iUserId;
					if (int.TryParse(sUserId, out iUserId))
					{
						return SiteUserExtended.Get(iUserId);
					}
				}

				return null;
			}
			set
			{
				Set(Keys.Uid,
					value != null && value.BaseInfo.UserId != null
						? Convert.ToBase64String(CryptoHelper.Encrypt(value.BaseInfo.UserId.Value.ToString()))
						: null);
			}
		}
	}
}
